<?php
/**
 * Text utility class
 * 
 * @author André Silva
 */
class Text {
	/**
	 * Encode a string, converting special chars
	 * @param string $param
	 * @return string
	 */
	public static function encode($param) {
		return htmlspecialchars($param, ENT_QUOTES);
	}

	/**
	 * Return a encoded string to original format
	 * @param string $param
	 * @return string 
	 */
	public static function decode($param) {
		return htmlspecialchars_decode($param, ENT_QUOTES);
	}
	
	/**
	 * Remove tags and encode text
	 * @param <type> $param Texto original
	 * @return <type> Texto pronto
	 */
	public static function strip($param, $allowed = '<p><a><b><i><s><strong>') {
		$param = strip_tags(self::decode($param), $allowed);
		$param = str_replace(PHP_EOL, '</p><p>', $param);
		return self::encode($param);
	}

	/**
	 * Truncate a string if the length is greater then the count size, and append "..."
	 * @param string $param
	 * @param int $count
	 * @return string
	 */
	public static function truncate($param, $count) {
		$param = substr($param, 0, $count) . (strlen($param) > $count ? '...' : '');
		return $param;
	}

	/**
	 * Convert a string to a URL format
	 * @param string $param
	 * @return string
	 */
	public static function urlEncode($param) {
		$param = strip_tags(stripcslashes(strtr(self::decode($param), 'áãàâéêíóôõúüçÁÃÀÂÉÊÍÓÔÕÚÜÇ ', 'aaaaeeiooouucAAAAEEIOOOUUC')));
		$param = ereg_replace('[^a-zA-Z0-9\-]', '-', $param);
		$param = ereg_replace('-+', '-', $param);
		$param = ereg_replace('^-|-$', '', $param);
		return $param;
	}
	
	/**
	 * Evaluate a string checking if have trace SQL Injection
	 * @param string $value
	 * @param boolean $value
	 * @return boolean
	 */
	public static function checkSqlInjection($value, $checkWords = false) {
		if ($checkWords) {
			$forbidden = '/(\;|\'|\"|\\|\*|\-|\=|\#|\(|\)|\%|from|select|update|insert|delete|where|drop|show|tables)/i';
		} else {
			$forbidden = '/(\;|\'|\"|\\|\*|\-|\=|\#|\(|\)|\%)/i';
		}
		if(preg_match($forbidden, $value)) {
			return true;
		}
		return false;
	}
}
?>